package handler

import (
	"github.com/gin-gonic/gin"
	"path/filepath"
	"strconv"
	"user-video/model"
	"user-video/pkg"
)

func Register(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	againPassword := c.PostForm("again_password")
	if username == "" || password == "" || againPassword == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名、密码、再次输入密码不为空",
		})
		return
	}
	user := model.User{
		Username:      username,
		Password:      pkg.Md5String(password),
		AgainPassword: pkg.Md5String(againPassword),
	}
	err := model.DB.Create(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "注册失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "注册成功",
		})
		return
	}
}

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	againPassword := c.PostForm("again_password")
	if username == "" || password == "" || againPassword == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名、密码、再次输入密码不为空",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ? and password = ? and again_password = ?", username, pkg.Md5String(password), pkg.Md5String(againPassword)).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "登录成功",
		})
		return
	}
}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	video := model.Video{
		Title:     title,
		Content:   content,
		Img:       img,
		LikeCount: 0,
		UserID:    userId,
	}
	err := model.DB.Create(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "发布成功",
		})
		return
	}
}

func Upload(c *gin.Context) {
	file, err := c.FormFile("img")
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件获取失败",
		})
		return
	}
	if file.Size > 2*1024*1024 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片大小不超过2M",
		})
		return
	}
	allow := map[string]bool{
		".jpg":  true,
		".png":  true,
		".jpeg": true,
	}
	ext := filepath.Ext(file.Filename)
	if !allow[ext] {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片格式不正确",
		})
		return
	}
	path := "static/img/" + file.Filename
	err = c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "上传失败",
		})
		return
	} else {
		url := "http://" + c.Request.Host + "/" + path
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "上传成功",
			"data": url,
		})
		return
	}
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var count int64
	model.DB.Model(&model.Video{}).Count(&count)
	var video []model.Video
	err := model.DB.Order("like_count desc").Preload("User").Offset(offset).Limit(size).Find(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": gin.H{
				"count": count,
				"video": video,
			},
		})
		return
	}
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var video model.Video
	err := model.DB.Preload("User").Where("id = ?", id).First(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": video,
		})
		return
	}
}

func Like(c *gin.Context) {
	userId, _ := strconv.Atoi(c.Query("user_id"))
	videoId, _ := strconv.Atoi(c.Query("video_id"))
	var like model.Like
	err := model.DB.Where("user_id = ? and video_id = ?", userId, videoId).Preload("User").Preload("Video").First(&like).Error
	if err == nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能重复点赞",
		})
		return
	}
	tx := model.DB.Begin()
	like = model.Like{
		UserID:  userId,
		VideoID: videoId,
	}
	err = tx.Create(&like).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞失败",
		})
		return
	}
	var video model.Video
	err = tx.Where("id = ?", videoId).First(&video).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "信息不存在",
		})
		return
	}
	video.LikeCount++
	err = tx.Save(&video).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "更新失败",
		})
		return
	} else {
		tx.Commit()
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "点赞成功",
		})
		return
	}
}
